import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
// import axios from './server/axios'//导入时默认导出可以随便命名
// import {getTopics,getTopic} from './server';//直接调用方法，但是写的方法多
import * as api from './server';//引入所有的方法
import './home.css';
import './App.css';
import dayjs from './server/day';
import Bottom from './Bottom';
import { Toast, NavBar } from 'antd-mobile';
// console.log(dayjs().from(dayjs()));

const Home = () => {
  const [topics, setTopics] = useState([]);

  useEffect(() => {

    api.getTopics()//把所有的请求写到一个文件中更简洁，等价于axios.get('/topics') 
      .then(res => {
        setTopics(res.data)
      })

  }, [])

  //发布
  const createTopic = () => {
    api.createTopic({
      accesstoken: 'e73b268b-f5d2-4ff1-8fd9-3581b84962e2',
      title: 'hello',
      tab: 'dev',
      content: '<h2>测试</h2>'
    })
      .then(res => {
        if (res.success) {
          alert('发布成功')
          Toast.show({
            icon: 'success',
            content: '发布成功'
          })
        }
      })
      .catch(err => {
        // console.dir(err.response.data.error_msg)
        Toast.show({//统一写到响应拦截中
          icon: 'fail',
          content: err.response.data.error_msg,
        })
      })
  }

  return (
    <div className='home'>
      <button onClick={createTopic}>发布主题</button>
      <ul className='topics'>
        {
          topics.map(item => {
            return <li key={item.id}>
              <Link to={`topic/${item.id}`}> {item.title}</Link>
              {/* <Link to='/topic'> {item.title}</Link>  
              topic后面加变量用差值表达式to={'topic/'+item.id}   
              或者用反引号to={`topic/${item.id}`}
              */}
              {/* dayjs().to(item.last_reply_at) */}
              <span className="time">{dayjs(item.last_reply_at).fromNow()}</span>
            </li>
          })
        }
      </ul>
      <div className="bottom"><Bottom /></div>

    </div>
  )
}

export default Home
